<template>
  <div class="motherboard-manage">
    <!-- 头部按钮部分 -->
    <div class="m-top">
      <div class="left">
        <a-input v-model:value="searchName" placeholder="请输入母版名称" />
        <a-button type="primary" class="search" @click="search">查询</a-button>
        <a-button type="primary" @click="reset">重置</a-button>
      </div>
      <div class="right">
        <a-button type="primary" @click="showModal()">新增母版</a-button>
      </div>
    </div>

    <!-- 卡片列表 -->
    <a-row :gutter="[20, 20]">
      <a-col :xs="24" :sm="12" :md="6" :lg="6" :xl="4" v-for="item in dataList" :key="item.id">
        <a-card hoverable style="">
          <template #cover>
            <a-image
              class="cover-img"
              :src="item.pic"
              fallback=""
            />
          </template>
          <template #actions>
            <div @click="showModal(item)"><edit-outlined key="edit" />编辑</div>
            <div @click="deleteMotherboard(item)"><delete-outlined />删除</div>
          </template>
          <a-card-meta :title="item.templateName"> </a-card-meta>
        </a-card>
      </a-col>
      <Empty v-if="!spinLoading && (!dataList || !dataList.length)" />
      <a-spin class="spin-loading" v-show="spinLoading" />
    </a-row>

    <!-- 新增弹出框 -->
    <a-modal
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      :maskClosable="false"
      centered
      :title="bouncedTitle"
      ok-text="确定"
      cancel-text="取消"
      class="bounced"
      @ok="onOk"
    >
      <a-form ref="formRef" :model="formState" layout="vertical" name="form_in_modal">
        <a-form-item name="templateName" label="母版名称" :rules="[{ required: true, message: '请输入母版名称!' }]">
          <a-input v-model:value="formState.templateName" />
        </a-form-item>
        <a-form-item name="route" label="路由地址" :rules="[{ required: true, message: '请输入路由地址!' }]">
          <a-input v-model:value="formState.route" />
        </a-form-item>
        <a-form-item name="pic" label="预览图" :rules="[{ required: false, message: '请上传预览图!' }]">
          <ImageSubmit @getImg="getImg" ref="imageRef" :photoList="photoList" fileNumber="1"></ImageSubmit>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'MotherboardManage'
}
</script>
<script setup>
/**
 * 母版配置
 * @author 阳坤（1194636148@qq.com）
 * @date   时间：2022/11
 */

import motherboardApi from '@/api/management/motherboard'
import { onMounted, ref, reactive, getCurrentInstance } from 'vue'
import ImageSubmit from '@/components/ImageSubmit.vue'
import { message } from 'ant-design-vue'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import Empty from '@/views/business-component/components/empty'

const { proxy } = getCurrentInstance()
// 根据名称搜索
const searchName = ref()
// 加载数据loading
const spinLoading = ref(true)
// 列表数据项
const dataList = ref([])

// 控制新增、修改弹框显示
const visible = ref(false)
const bouncedTitle = ref('新增母版')
// 新增提交异步loading
const confirmLoading = ref(false)

// 表单数据
const formState = reactive({
  route: '', // 路由地址
  templateName: '', // 母版名称
  pic: '', // 预览图
  id: null // id
})
// 回显的图片列表
const photoList = ref([])
// 表单ref对象
const formRef = ref()
// 图片上传ref对象
const imageRef = ref()

onMounted(() => {
  init()
})

/**
 *  初始化
 */
const init = () => {
  getData()
}

/**
 *  根据条件搜索
 */
const search = () => {
  getData({
    routerPath: null,
    templateName: searchName.value
  })
}

/**
 *  重置条件搜索
 */
const reset = () => {
  searchName.value = ''
  getData({
    routerPath: '',
    templateName: ''
  })
}

/**
 *  获取数据
 */
const getData = searchParams => {
  spinLoading.value = true
  dataList.value = []
  motherboardApi
    .getMotherboardList(searchParams || {})
    .then(res => {
      if (res.data && res.data.length) {
        dataList.value = res.data
      }
    })
    .finally(() => {
      spinLoading.value = false
    })
}

/**
 *  点击删除  气泡确认
 */
const deleteMotherboard = item => {
  proxy.$confirm({
    title: '确定删除该母版吗？',
    onOk: () => {
      motherboardApi.deleteMotherboard({ id: item.id }).then(res => {
        if (res.data) {
          const index = dataList.value.findIndex(value => value.id == item.id)
          dataList.value.splice(index, 1)
        }
      })
    }
  })
}

/**
 *  显示新增、修改弹框
 */
const showModal = item => {
  if (imageRef.value && imageRef.value.fileList) {
    imageRef.value.fileList = []
  }
  if (item) {
    bouncedTitle.value = '修改母版'
    formState.route = item.route
    formState.templateName = item.templateName
    formState.pic = null // item.pic
    formState.id = item.id
    // 回显图片
    photoList.value = [
      {
        name: '',
        status: 'done',
        url: item.pic
      }
    ]
  } else {
    bouncedTitle.value = '新增母版'
    formState.route = ''
    formState.templateName = ''
    formState.pic = ''
    delete formState.id
    photoList.value = []
  }
  visible.value = true
}

/**
 *  获取图片
 */
const getImg = (file, url) => {
  file.append('type', 'parent-template') // parent-template:母版图片, component:组件

  motherboardApi
    .uploadImage(file)
    .then(async res => {
      if (res.detail) {
        imageRef.value.fileList = [
          {
            name: file.name,
            status: 'done',
            url: url
          }
        ]
        formState.pic = res.detail
      }
    })
    .catch(() => {
      imageRef.value.fileList = [
        {
          name: 'image.png',
          status: 'error'
        }
      ]
      message.error('图片上传失败')
    })
}

/**
 *  点击表单确定
 */
const onOk = e => {
  formRef.value
    .validateFields()
    .then(async values => {
      confirmLoading.value = true
      let data = null
      if (bouncedTitle.value == '新增母版') {
        data = await motherboardApi.addMotherboard(formState)
        if (data.data) {
          dataList.value.unshift(data.data)
        }
      } else {
        data = await motherboardApi.editMotherboard(formState)
        if (data.data) {
          getData()
        }
      }
      if (data.data) {
        formRef.value.resetFields()
        visible.value = false
      }
      confirmLoading.value = false
    })
    .catch(info => {
      console.log('Validate Failed:', info)
    })
}
</script>

<style scoped lang="less">
.motherboard-manage {
  height: 100%;
  display: flex;
  flex-direction: column;

  .m-top {
    .search {
      margin: 0 20px;
    }
  }

  /deep/.ant-row {
    overflow-y: auto;
    padding: 5px 0;
    .ant-card-cover {
      height: 150px;
      .ant-image {
        height: 100%;
        .cover-img {
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }

  .empty {
    width: 100%;
  }

  .spin-loading {
    width: 100%;
    min-height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>

<style scoped>
.bounced {
  width: 600px !important;
}
</style>
